#include "stdafx.h"
#include "fontprovider.h"

CFontProvider::CFontProvider() 
#ifdef __SYMBIAN32__
	: iCache(NULL)
#endif
{
	iCache = new (ELeave) CFontCache;
}

CFontProvider::~CFontProvider()
{
	CFont* font;
	while ((font = iCache->RemoveFirstEntry()) != NULL)
	{
		CCoeEnv::Static()->ScreenDevice()->ReleaseFont( font );
	}

	if(iCache != NULL)
	{
		delete iCache;
		iCache = NULL;
	}
}

const CFont& CFontProvider::MakeFontL(TInt aFontSize, TBool aIsItalic, TBool aIsBold, TBool aIsAntiAliased) const
{
	//	_LIT(KFontFamilyMonospace, "Monospace");

	// 构造新字体描述
	//	TFontSpec fontSpec;
	//	fontSpec.iTypeface = iNormalFont.FontSpecInTwips().iTypeface;
	//	fontSpec.iHeight = aFontSize + iNormalFont.FontMaxDescent();

	//	aFontSize += CCoeEnv::Static()->NormalFont()->FontStandardDescent(); // + 2;

	// webkit code:
	TBool iApac = ETrue;
	TInt sizeInTwips = CCoeEnv::Static()->ScreenDevice()->VerticalPixelsToTwips(iApac ? (aIsBold ? Max(aFontSize, 11) : aFontSize) : aFontSize);

	//	_LIT(FONT_CH16, "CombinedChinesePlain12");

	TFontSpec fontSpec;
	//	fontSpec.iTypeface.iName = FONT_CH16;
	//	fontSpec.iTypeface.SetIsProportional(EFalse);
	fontSpec.iTypeface = CCoeEnv::Static()->NormalFont()->FontSpecInTwips().iTypeface;
	fontSpec.iHeight = sizeInTwips;

	// 反锯齿
	fontSpec.iFontStyle.SetBitmapType(aIsAntiAliased ? EAntiAliasedGlyphBitmap : EDefaultGlyphBitmap);

	// 斜体
	fontSpec.iFontStyle.SetPosture(aIsItalic ? EPostureItalic : EPostureUpright);

	// 粗体
	fontSpec.iFontStyle.SetStrokeWeight(aIsBold ? EStrokeWeightBold : EStrokeWeightNormal);

	// 在缓冲中查找字体描述
	CFont* result = iCache->Search(fontSpec);
	if (!result)
	{
		// 构造新字体
		CCoeEnv::Static()->ScreenDevice()->GetNearestFontInTwips(result, fontSpec);
		iCache->AddEntryL(result, fontSpec);
	}

	return *result;
}
